//
//  QDTicketTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/3.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON

/// 车票列表
final class QDTicketTableViewController: NWTableViewController {

    /// 列表类型
    var type: QDTickeStatusType = .success
    /// 所有的票
    private var tickets = [QDTicket]()
    
    convenience init(type: QDTickeStatusType) {
        self.init()
        self.type = type
    }
    
    override func loadPropertysAtInitialization() {
        
        super.loadPropertysAtInitialization()
        tableView.rowHeight = 105
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDTicketTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    override func nothingTitle() -> String? { return "暂无记录" }
    override func nothingImage() -> UIImage? { return "nothing_ticket".namedImage }
    override func nothingImageOffset() -> CGFloat { return -96.5 }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //请求列表
        requestTicketList()
        //订阅通知
        NotificationCenter.default.addObserver(self, selector: #selector(ticketStatusDidChanged), name: QDTicketStatusDidChangedNotificationName, object: nil)
    }
    
    /// 车票状态发生变化
    @objc func ticketStatusDidChanged(){
        headerRefreshBeginHandler()
    }
    
    
    override func headerRefreshBeginHandler() {
        currentPage = 0
        tableView.mj_footer.resetNoMoreData()
        requestTicketList()
    }
    
    
    override func footerRefreshBeginHandler() {
        requestTicketList()
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    

    //TableView
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tickets.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let ticketCell = cell as? QDTicketTableViewCell {
            
            let ticket = tickets[indexPath.row]
            
            //赋值
            ticketCell.startLabel.text = ticket.entryStation
            ticketCell.endLabel.text = ticket.exitStation
            
            let price = (Double(ticket.ticketAmount) ?? 0.0) / 100.0
            ticketCell.subtitleLabel.text = "购买数量：\(ticket.ticketCount)张  |  总价：\(NSString(format: "%.2f", Double(price)))元"
            ticketCell.timeLabel.text = "支付时间：\(ticket.statusTime)"
            
            ticketCell.statusImageView.image = ticket.state.statusImage
            ticketCell.actionButton.isHidden = !(ticket.state == .unPay || ticket.state == .unTakeout)
            ticketCell.actionButton.setTitle(ticket.state == .unPay ? "立即支付" :"扫码取票", for: .normal)
            
            //点击响应
            ticketCell.actionButtonTapHandler = { [unowned self] in
//                self.tableView(tableView, didSelectRowAt: indexPath)
                self.ritl_topNavigationPush(QDTicketDetailViewController(orderNum: self.tickets[indexPath.row].orderNo), animated: true)
            }
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //跳转详情
        ritl_topNavigationPush(QDTicketDetailViewController(orderNum: tickets[indexPath.row].orderNo), animated: true)
    }
}


extension QDTicketTableViewController {
    
    /// 请求车票列表
    private func requestTicketList(){
        
        QDNetworkingManager.requestTicketList(type: type, page: currentPage, complete: { (datas) in
            
            self.endHeaderRefreshing()
            self.endFooterRefreshing()
            
            if self.currentPage == 0 {
                self.tickets.removeAll()
            }
            
            self.tickets += datas
            self.currentPage += 1
            
            print("\n\n\n返回来\(datas.count)张\n\n\n")
            
            if datas.count < 10 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            
            if self.tickets.count == 0 {
                // 没有订单信息
                self.showNothingView(true)
            }else {
                self.showNothingView(false)
            }
            
        }) { (msg, errorType) in
            
            self.endHeaderRefreshing()
            self.endFooterRefreshing()
            self.view.showTextHUD(text: msg)
        }
    }
}



extension QDNetworkingManager {
    
    /// 请求车票订单
    static func requestTicketList(type: QDTickeStatusType,page: Int = 0,complete:@escaping (([QDTicket])->()),fail: QDNetworkingError?){
        
        request(url: onlineTicketListUrl, isArray: true, paramteres: ["displayType":type.rawValue,"page":page, "size": 10], arraySuccess: { (msg, datas) in
            
            guard let tickets = [QDTicket].deserialize(from: datas) else {
                fail?(msg,.unknowned); return
            }
            
            complete(tickets as! [QDTicket])
            
        }) { (msg, errorType) in
            
            fail?(msg, errorType)
        }
    }
}
